/**
 * Created by 55456 on 2016/4/9.
 */
var db = require("../../models/index");
var codeConfig = require("../../configs/codeConfig");
var appConfig  = require("../../configs/appConfig");
var auth = require("../../helpers/auth");
var storyAdaptor = require("../../modelsAdaptor/storyAdaptor");
var uuid = require('node-uuid');
var autoPrefix = appConfig.autoPrefix;

module.exports = (router) => {
    var User = db.models.User;
    var Story = db.models.Story;
    var UserStory = db.models.UserStory;

    router.post(autoPrefix("storylist/:page/:Count"),function *(){
        this.checkBody("userID").notEmpty();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var userID = body.userID;
        var page = this.params.page;
        var count = this.params.Count;
        var isOwn = userID === (yield auth.user(this)).id;
        //todo:parse and define return data format out
        var user = yield User.findOne({
            where:{
                id:userID
            },
            attributes: { exclude: ["password"] }
        });
        var stories = yield storyAdaptor.getStoryByUserID(userID,isOwn,page,count);
        this.body = codeConfig.parseMsg({user:user,stories:stories});
    });

    router.post(autoPrefix("story"),function *(){
        this.checkBody("storyID").notEmpty();
        this.checkBody("AuthorID").notEmpty();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var isOwn = body.AuthorID === (yield auth.user(this)).id;
        var storyID = body.storyID;
        var story = yield storyAdaptor.getStoryByStoryID(storyID);
        this.body = codeConfig.parseMsg({story:story,isOwn:isOwn});
    });

    router.post(autoPrefix("addstory"),function *(){
        this.checkBody("title").notEmpty();
        this.checkBody("flags").notEmpty();
        this.checkBody("content").notEmpty();
        this.checkBody("publicEnable").notEmpty();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var id = uuid.v1();
        var story = {
            id : id,
            title:body.title,
            content:body.content,
            flags:body.flags,
            publicEnable : body.publicEnable,
            AuthorID : (yield auth.user(this)).id
        };
        story = yield Story.create(story);
        var h5Url = appConfig.h5Url + story.id;
        var data = {
            id : story.id,
            h5Url : h5Url
        };
        this.body = codeConfig.parseMsg(data);
    });

    router.post(autoPrefix("story/like"),function *(){
        this.checkBody("storyID").notEmpty();
        this.checkBody("isLike").notEmpty().toInt();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var userID = (yield auth.user(this)).id;
        try {
            yield UserStory.update({
                isLike: body.isLike
            }, {
                where: {
                    UserId: userID,
                    StoryId: body.storyID
                }
            });
        }catch(err){
            console.log(err);
            this.body = codeConfig.parseErrorMsg(err);
            return;
        }
        this.body = codeConfig.parseMsg(true);
    });

    router.post(autoPrefix("story/collect"),function *(){
        //todo:如果收藏的故事以后被转成private了怎么办
        this.checkBody("storyID").notEmpty();
        this.checkBody("isCollect").notEmpty().toInt();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var userID = (yield auth.user(this)).id;
        try {
            yield UserStory.update({
                isCollect: body.isCollect
            }, {
                where: {
                    UserId: userID,
                    StoryId: body.storyID
                }
            });
        }catch(err){
            console.log(err);
            this.body = codeConfig.parseErrorMsg(err);
            return;
        }
        this.body = codeConfig.parseMsg(true);
    });

    router.post(autoPrefix("public/storylist/:page/:Count"),function *(){
        this.checkParams("page").notEmpty().toInt();
        this.checkParams("Count").notEmpty().toInt();
        this.checkBody("timestamps").notEmpty().toString();
        if(this.errors){
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var timestamps = this.request.body.timestamps;
        var page = this.params.page;
        var count  = this.params.Count;
        var data = yield storyAdaptor.getAllPublicStories(page,count,timestamps);
        this.body = codeConfig.parseMsg(data);
    });

    /**
     * 故事列表的修改
     * 唯一问题是如果一台设备修改后没有提交
     * 另一台设备修改后也没有提交
     * 最后两者一起提交了，这个时候怎么处理
     * 现在是直接覆盖掉
     */
    router.post(autoPrefix("changeStory"),function *(){
        var ctx = this;
        ctx.checkBody('storyId').notEmpty();
        ctx.checkBody('content').notEmpty();
        ctx.checkBody('title').notEmpty();
        ctx.checkBody('publicEnable').notEmpty().toInt();
        ctx.checkBody('flags').notEmpty();
        if(ctx.errors){
            ctx.body = codeConfig.parseErrorMsg(ctx.errors);
            return;
        }
        var body = ctx.request.body;
        var user = yield auth.user(ctx);
        var story = yield Story.findOne({
            where:{
                id : body.storyId
            }
        });
        if( ! story) {
            ctx.body = codeConfig.parseErrorMsg('story not exist');
            return;
        }
        if(story.AuthorID !== user.id){
            ctx.body = codeConfig.parseErrorMsg('not your story');
            return;
        }
        yield Story.update({
            title : body.title,
            content : body.content,
            flags : body.flags
        },{
            where : {
                id : body.storyId
            }
        });
        story = yield Story.findOne({
            where:{
                id : body.storyId
            }
        });
        ctx.body = codeConfig.parseMsg(story);
    });

    router.post(autoPrefix("delStory"),function *(){
        var ctx = this;
        ctx.checkBody('storyId').notEmpty();
        if(ctx.errors){
            ctx.body = codeConfig.parseErrorMsg(ctx.errors);
            return;
        }
        var body = ctx.request.body;

        //查找到storyId对应的故事，然后删除
        var story = yield Story.findOne({
            where:{
                id : body.storyId
            }
        });
        if(! story) {
            ctx.body = codeConfig.parseErrorMsg('story has been deleted');
            return;
        }
        yield Story.destroy({
            where : {
                id : body.storyId
            }
        });

        ctx.body = codeConfig.parseMsg('success');
    });

};